package middleware

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strings"
	"time"
	"web_api_gin/dao"
	"web_api_gin/entity"
)

// 记录日志
func optLogRecord(ctx *gin.Context) {
	//请求之后记录日志
	ctx.Next()
	defer func() {
		//获取当前权限数据
		var permData entity.SysPermission
		permDataGlobal := ctx.Value("permData")
		permJsonStr, _ := json.Marshal(permDataGlobal)
		json.Unmarshal(permJsonStr, &permData)
		//是否记录日志
		isRecordLog := false
		method := strings.ToLower(ctx.Request.Method)
		if method == "post" || method == "PUT" {
			isRecordLog = true
		} else {
			if permData.PermId != 0 && permData.IsOpertionLog == true {
				isRecordLog = true
			}
		}
		if isRecordLog {
			//获取当前用户数据
			var userData entity.SysUsers
			userDataGlobal := ctx.Value("userData")
			userJsonStr, _ := json.Marshal(userDataGlobal)
			json.Unmarshal(userJsonStr, &userData)
			//路由名称
			var operationNameArr []string
			if permData.PermId != 0 {
				//面包屑
				if permBreadcrumb, err := dao.SysPermission.GetBreadcrumbList(ctx, permData.PermId, false); err == nil {
					for _, permission := range permBreadcrumb {
						operationNameArr = append(operationNameArr, permission.DisplayName)
					}
				}

			}
			formData := ctx.Value("formData")
			formDataStr, _ := json.Marshal(formData)
			data := entity.SysOptLog{
				UserId:       userData.Id,
				UserName:     userData.Name,
				OpertionName: strings.Join(operationNameArr, "->"),
				PermId:       permData.PermId,
				RouteName:    permData.Name,
				Url:          ctx.Request.URL.String(),
				IP:           ctx.ClientIP(),
				RequestData:  string(formDataStr),
				AddTime:      time.Now().Unix(),
			}
			dao.SysOptLog.SaveLog(ctx, &data)
		}
	}()
}
